package com.ruoyi.rsikManage.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import com.ruoyi.common.GenericMethodsService;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.electronicFence.service.A;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.rsikManage.AlarmTypeDic.domain.TAlarmTypeDicRequest;
import com.ruoyi.rsikManage.domain.*;
import com.ruoyi.rsikManage.domain.common.StatisticsRequest;
import com.ruoyi.rsikManage.domain.vo.*;
import com.ruoyi.rsikManage.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

@RequestMapping("monitorPoint")
@RestController
public class MonitorPointController extends BaseController {

    @Value("${jy.ip}")
    private String JY_IP;
    @Value("${jy.port}")
    private String JY_LOGIN_PORT;

    @Value("${video.manufacturer_name}")
    private String VIDEO_MANUFACTURER_NAME;

    @Value("${system.ip}")
    private String SERVER_IP;
    @Value("${system.web_port}")
    private String WEB_PORT;
    @Autowired
    JyService jyService;
    @Autowired
    MonitorPointService monitorPointService;
    @Autowired
    AlgorithmService algorithmService;
    @Autowired
    ITVideoStandPlaceService tVideoStandPlaceService;
    @Autowired
    VideoDiagnosisController videoDiagnosisController;
    @Autowired
    VideoResourceTreeService videoResourceTreeService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private GenericMethodsService genericMethodsService;


    public MonitorPointService getMonitorPointService() {
        return monitorPointService;
    }

    @Autowired
    private ITDiagnosisDataService tDiagnosisDataService;


    @Autowired
    private ITUnitConfigService iTUnitConfigService;


    /**
     * 查询所有gis监控点
     */
    @GetMapping("allGisMonitors")
    public TableDataInfo selectAllGisMonitors(GisMonitorsVo gisMonitorsVo) {
        startPage();
        List<GisMonitorsVo> res = monitorPointService.selectAllGisMonitors(gisMonitorsVo);
        return getDataTable(res);
    }
    /**
     * 查询有坐标的gis监控点
     */
    @GetMapping("gisMonitorsHasCoordinates")
    public TableDataInfo gisMonitorsHasCoordinates() {
        List<GisMonitorsVo> res = monitorPointService.gisMonitorsHasCoordinates();
        return getDataTable(res);
    }
    /**
     * 配置监控点的Gis坐标
     */
    @PutMapping("updateGisMonitorsCoordinates")
    private AjaxResult updateGisMonitorsCoordinates(@Validated @RequestBody GisMonitorsVo gisMonitorsVo) {
        monitorPointService.updateGisMonitorsCoordinates(gisMonitorsVo);
        return AjaxResult.success();
    }
    /**
     * 3D 查询所有gis监控点
     */
    @GetMapping("allMonitors3D")
    public TableDataInfo selectAllMonitors3D(GisMonitors3DVo gisMonitors3DVo) {
        startPage();
        List<GisMonitors3DVo> res = monitorPointService.selectAllMonitors3D(gisMonitors3DVo);
        return getDataTable(res);
    }
    /**
     * 3D 查询有3D坐标的监控点
     */
    @GetMapping("gisMonitorsHas3DCoordinates")
    public TableDataInfo gisMonitorsHas3DCoordinates() {
        startPage();
        List<GisMonitors3DVo> res = monitorPointService.gisMonitorsHas3DCoordinates();
        return getDataTable(res);
    }
    /**
     * 3D 配置监控点的3D坐标
     */
    @PutMapping("updateGisMonitors3DCoordinates")
    private AjaxResult updateMonitors3DCoordinates(@Validated @RequestBody GisMonitors3DVo gisMonitors3DVo) {
        monitorPointService.updateMonitors3DCoordinates(gisMonitors3DVo);
        return AjaxResult.success();
    }

    /**
     * 查询各煤矿，及其分类下的监控点
     */
    @GetMapping("coalMinesAndMonitors/v1")
    public AjaxResult selectCoalMinesAndMonitors(String monitorName ){
        HashMap<String, Object> resMap = new HashMap<>();
        HashMap<String, Integer> map = monitorPointService.selectTotalMonitorCountAndOnlineMonitorCount();
        resMap.put("coalMineList", monitorPointService.selectCoalMinesWithMonitors(monitorName));
        resMap.put("totalMonitorCount", map.get("totalMonitorCount"));
        resMap.put("onlineMonitorCount", map.get("onlineMonitorCount"));
        return success(resMap);
    }

    /**
     * 查询各煤矿，及其分类下的监控点
     */
    @GetMapping("coalMinesAndMonitors")
    public AjaxResult selectCoalMinesAndMonitors(String monitorName,String isOnline,Long unitCode ,HttpServletRequest httpServletRequest){

        if (unitCode==null){
            // 如果单位代码列表为空，则尝试从当前登录用户获取单位代码
            if (httpServletRequest != null && tokenService.getTokenInfo(httpServletRequest) != null) {
                unitCode = tokenService.getLoginUserUnitCode(httpServletRequest);
            }
        }


        HashMap<String, Object> resMap = new HashMap<>();
        HashMap<String, Integer> map = monitorPointService.selectMonitorStatusCount(unitCode,null);
        resMap.put("coalMineList", monitorPointService.selectCoalMinesWithMonitorsForUnitCodes(unitCode,monitorName,isOnline,null));
        resMap.put("totalMonitorCount", map.get("totalMonitorCount"));
        resMap.put("onlineMonitorCount", map.get("onlineMonitorCount"));
        return success(resMap);
    }

    /**
     * 查询各煤矿，及其分类下的监控点
     */
    @PostMapping("coalMinesAndMonitors/list")
    public AjaxResult selectCoalMinesAndMonitorsForUnitCodes(@RequestBody(required = false) StatisticsRequest statisticsRequest,
                                                             HttpServletRequest httpServletRequest) {
        Long unitCode = statisticsRequest.getUnitCode();
        String apeName = statisticsRequest.getApeName();
        String apeId = statisticsRequest.getApeId();
        String isOnline = statisticsRequest.getIsOnline();

        // 初始化单位代码列表
        List<Long> unitCodes = new ArrayList<>();
        // 如果请求体不为空，则从请求体中获取单位代码
        if (statisticsRequest != null &&
            statisticsRequest.getUnitCodes()!=null &&
            statisticsRequest.getUnitCodes().size()>0) {
            unitCodes = statisticsRequest.getUnitCodes();
        }
        // 如果单位代码列表为空，则尝试从当前登录用户获取单位代码
        if (CollectionUtils.isEmpty(unitCodes)) {
            if (httpServletRequest != null && tokenService.getTokenInfo(httpServletRequest) != null) {
                unitCodes = tokenService.getLoginUserUnitCodes(httpServletRequest);
            }
        }
        ArrayList<HashMap<String, Object>> resultList = new ArrayList<>();
        Map<Long, SysDept> deptMap = genericMethodsService.getDeptMap();
        for (Long unit: unitCodes){
            HashMap<String, Object> resultMap = new HashMap<>();
            SysDept dept = deptMap.get(unit);
            if (dept != null) {
                String deptName = dept.getDeptName();
                resultMap.put("unitCode",unit);
                resultMap.put("unitName",deptName);
                HashMap<String, Object> resMap = new HashMap<>();
                HashMap<String, Integer> map = monitorPointService.selectMonitorStatusCount(unit,unitCodes);
                resMap.put("coalMineList", monitorPointService.selectCoalMinesWithMonitorsForUnitCodes(unit,apeName,isOnline,unitCodes));
                resMap.put("totalMonitorCount", map.get("totalMonitorCount"));
                resMap.put("onlineMonitorCount", map.get("onlineMonitorCount"));
                resultMap.put("resMapList",resMap);
                resultList.add(resultMap);
            }
        }
        AjaxResult success = AjaxResult.success(resultList);

        return success;
    }
    /**
     * 查询某个场所下的所有监控点的视频回放url
     */
    @GetMapping("getReplayStreamUrl")
    public TableDataInfo getMonitorsReplayStreamUrl(@RequestParam("startTime") String startTime,
                                                    @RequestParam("endTime")String endTime,
                                                    Long placeId,
                                                    String monitorId) {
        startPage();
        List<MonitorPoint> resList = null;
        if (monitorId != null) {
            resList = new ArrayList<>();
            resList.add(monitorPointService.selectMonitorByApeId(monitorId));
        }
        else if (placeId != null) {
            resList = monitorPointService.selectMonitorPointsInPlace(placeId);
        }else {
            resList = monitorPointService.selectAllMonitorPoints();
        }

        //查询各监控点的视频回放url
        for (MonitorPoint monitor : resList) {
            try {
                String liveStreamUrl = jyService.getLiveStreamUrlOfTheMonitor(monitor.getApeId(),"0", "1", "100", "");
                monitor.setReplayStreamUrl(liveStreamUrl);
            }catch (Exception e) {
                monitor.setReplayStreamUrl(null);
            }

        }
        return getDataTable(resList);
    }

    /**
     * 1.统计监控点实时在线率 √
     */
    @GetMapping("count-online-rate/v2")
    public AjaxResult countOnlineRate() {
        return success(monitorPointService.countOnlineRate());
    }

    /**
     * 1.统计监控点实时在线率 √ V2
     */
    @PostMapping("count-online-rate")
    public AjaxResult countOnlineRateForUnitCodes(@RequestBody StatisticsRequest statisticsRequest,
                                                  HttpServletRequest httpServletRequest) {
        List<Long> unitCodes = statisticsRequest.getUnitCodes();
        if (unitCodes == null || unitCodes.isEmpty()){
            if( httpServletRequest != null && tokenService.getTokenInfo(httpServletRequest) != null){
                unitCodes = tokenService.getLoginUserUnitCodes(httpServletRequest);
            }
        }

        return success(monitorPointService.countOnlineRateForUnitCodes(unitCodes));
    }
    /**
     * 2.统计监控点诊断结果的达标率 √
     */
//    @GetMapping("count-compliance-ratio")
//    public AjaxResult countComplianceRatio() {
//        return success(monitorPointService.countComplianceRatio());
//    }
    @GetMapping("count-compliance-ratio/v2")
    public AjaxResult countComplianceRatio() {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("page_num", 1);
        paramMap.put("page_size",9999);
        String jsonStr = jyService.getLastVideoDiagnosisResult(paramMap);
        HashMap<String, Integer> diagnosisResultMap = countNumberOfEachDiagnosisResult(jsonStr);
        List<HistogramVo> resList = buildDiagnosisResultList(diagnosisResultMap);
        //
        NumberFormat percentFormat = NumberFormat.getPercentInstance();
        percentFormat.setMaximumFractionDigits(2);
        String ratio = percentFormat.format((double)diagnosisResultMap.get("1") / (diagnosisResultMap.get("1") +
                diagnosisResultMap.get("2") + diagnosisResultMap.get("3") + diagnosisResultMap.get("4")));
        //
        RatioVo ratioVo = new RatioVo();
        ratioVo.setValue(ratio);
        ratioVo.setData(resList);
        ratioVo.setDesc("实时获取最后一次的诊断结果，\n" +
                "达标率 = 达标数 / (达标数 + 一般数 + 很差数 + 失败数) * 100%\n" +
                "\n" +
                "达标：实时获取最后一次的诊断的达标结果\n" +
                "一般：实时获取最后一次的诊断的一般结果\n" +
                "很差：实时获取最后一次的诊断的很差结果\n" +
                "失败：实时获取最后一次的诊断的失败结果");
        return success(ratioVo);
    }

    /**
     * 2.统计监控点诊断结果的达标率 √
     *   修改时间 24/10/25
     *   修改内容 GET->POST
     */
    @PostMapping ("count-compliance-ratio")
    public AjaxResult countComplianceRatioForUnitCodes(@RequestBody StatisticsRequest statisticsRequest,
                                                       HttpServletRequest httpServletRequest) {

        List<Long> unitCodes = statisticsRequest.getUnitCodes();
        if (unitCodes==null || unitCodes.isEmpty()){
            unitCodes=tokenService.getLoginUserUnitCodes(httpServletRequest);
        }
        TUnitConfig tUnitConfig = new TUnitConfig();
        tUnitConfig.setUnitCodes(unitCodes);
        List<TUnitConfig> tUnitConfigs = iTUnitConfigService.selectTUnitConfigList(tUnitConfig);

        List<String>  DiagnosisList = new ArrayList<>();
        for (TUnitConfig Unit: tUnitConfigs){
            HashMap<String, Object> paramMap = new HashMap<>();
            paramMap.put("page_num", 1);
            paramMap.put("page_size",9999);
            String jsonStr = jyService.getLastVideoDiagnosisResultForUnitCodes(Unit,paramMap);
            DiagnosisList.add(jsonStr);
        }
        HashMap<String, Integer> diagnosisResultMap = countNumberOfEachDiagnosisResultForUnitCodes(DiagnosisList);

        List<HistogramVo> resList = buildDiagnosisResultList(diagnosisResultMap);
        //
        NumberFormat percentFormat = NumberFormat.getPercentInstance();
        percentFormat.setMaximumFractionDigits(2);
        String ratio="";
        int sum =diagnosisResultMap.get("1") + diagnosisResultMap.get("2") + diagnosisResultMap.get("3") + diagnosisResultMap.get("4");
        if (sum!=0){
            ratio = percentFormat.format((double)diagnosisResultMap.get("1") / sum);
        }
        else {
            ratio="0";
        }
        //
        RatioVo ratioVo = new RatioVo();
        ratioVo.setValue(ratio);
        ratioVo.setData(resList);
        ratioVo.setDesc("实时获取最后一次的诊断结果，\n" +
                "达标率 = 达标数 / (达标数 + 一般数 + 很差数 + 失败数) * 100%\n" +
                "\n" +
                "达标：实时获取最后一次的诊断的达标结果\n" +
                "一般：实时获取最后一次的诊断的一般结果\n" +
                "很差：实时获取最后一次的诊断的很差结果\n" +
                "失败：实时获取最后一次的诊断的失败结果");
        return success(ratioVo);
    }


    /**
     * 10. 统计不同摄像机类型的监控点个数
     */
    @GetMapping("count-camera-type/v2")
    public AjaxResult countCameraTypeTest() {
        HashMap<String, Integer> map = monitorPointService.selectTotalMonitorCountAndOnlineMonitorCount();
        List<HistogramVo> cameraTypeVoList = monitorPointService.selectCameraTypeWithMonitorNumber();

        RatioVo ratioVo = new RatioVo();
        ratioVo.setValue(map.get("totalMonitorCount") + "");
        ratioVo.setData(cameraTypeVoList);
        ratioVo.setDesc("实时更新，\n" +
                "总数 = 球机 + 半球机 + 固定枪机 + 遥控枪机 + 卡口枪机 + 其他类型");

        return success(ratioVo);
    }

    /**
     * 10. 统计不同摄像机类型的监控点个数
     */

    // @PreAuthorize("@ss.hasPermi('rsikManage:point:status-count')")
    //    @PostMapping ("count-camera-type")
    @RequestMapping(value = "/count-camera-type", method = {RequestMethod.GET, RequestMethod.POST})
    public AjaxResult countCameraTypeTestForUnitCodes(@RequestBody (required = false) StatisticsRequest statisticsRequest,
                                                      HttpServletRequest httpServletRequest) {
        // 初始化单位代码列表
        List<Long> unitCodes = new ArrayList<>();

        if (statisticsRequest!=null){
            unitCodes = statisticsRequest.getUnitCodes();
        }

        // 如果单位代码列表为空，则尝试从当前登录用户获取单位代码
        if (unitCodes == null || unitCodes.isEmpty()) {
            if (httpServletRequest != null && tokenService.getTokenInfo(httpServletRequest) != null) {
                unitCodes = tokenService.getLoginUserUnitCodes(httpServletRequest);
            }
        }
        HashMap<String, Integer> map = monitorPointService.selectTotalMonitorCountAndOnlineMonitorCountForUnitCodes(null,unitCodes);
        List<HistogramVo> cameraTypeVoList = monitorPointService.selectCameraTypeWithMonitorNumberForUnitCodes(unitCodes);

        RatioVo ratioVo = new RatioVo();
        ratioVo.setValue(map.get("totalMonitorCount") + "");
        ratioVo.setData(cameraTypeVoList);
        ratioVo.setDesc("实时更新，\n" +
                "总数 = 球机 + 半球机 + 固定枪机 + 遥控枪机 + 卡口枪机 + 其他类型");

        return success(ratioVo);
    }

    /**
     * 查询所有监控点信息（不关联其他的表信息）
     */
    @GetMapping("list")
    public AjaxResult selectMonitorList(String monitorName) {
        if (monitorName == null) {
            return success(monitorPointService.selectAllMonitorPoints());
        }else {
            return success(monitorPointService.selectMonitorPoints(monitorName));
        }
    }
    /**
     * 查询监控点离线报警的设定时间
     */
    @GetMapping("offline-alarm-setting-time")
    public AjaxResult selectMonitorsOfflineAlarmSettingTime(MonitorOfflineAlarmSettingRespVo monitorOfflineAlarmSettingRespVo) {
        List<MonitorOfflineAlarmSettingRespVo> res = monitorPointService.selectMonitorsOfflineAlarmSettingTime(monitorOfflineAlarmSettingRespVo);
        return AjaxResult.success(res);
    }

    /**
     * 配置监控点的离线报警设定时间
     */
    @PutMapping("offline-alarm-setting-time")
    public AjaxResult updateOfflineAlarmSettingTime(@Validated @RequestBody MonitorOfflineAlarmSettingResqVo monitorOfflineAlarmSetting) {
        Integer hours = monitorOfflineAlarmSetting.getHours();
        Integer minutes = monitorOfflineAlarmSetting.getMinutes();
        monitorOfflineAlarmSetting.setSetMinutes(hours * 60 + minutes);
        monitorPointService.updateOfflineAlarmSettingTime(monitorOfflineAlarmSetting);
        return success();
    }



    /**
     * 监控点管理：查询监控点列表
     */
    @GetMapping("/selectMonitorDetail")
    public TableDataInfo selectMonitorDetailList(MonitorPoint monitorPoint, VideoResourceTreeNode treeNode, HttpServletRequest httpServletRequest) {

        if (monitorPoint.getUnitCodes()==null||monitorPoint.getUnitCodes().size()==0 ){
            List<Long> unitCodes = tokenService.getLoginUserUnitCodes(httpServletRequest);
            monitorPoint.setUnitCodes(unitCodes);
        }
        startPage();
        List<MonitorPoint> monitorPoints = monitorPointService.selectMonitorsDetail(monitorPoint, treeNode);
        for (MonitorPoint m : monitorPoints) {
            m.setAlgorithmList(algorithmService.algorithmsInTheMonitor(m.getApeId()));
        }
        return getDataTable(monitorPoints);
    }

    /**
     * 监控点管理：查询监控点列表
     */
    @PostMapping("/selectMonitorDetail/list")
    public TableDataInfo selectMonitorDetailListForUnitCodes(@RequestBody MonitorPoint monitorPoint, HttpServletRequest httpServletRequest) {

        List<Long> unitCodes = monitorPoint.getUnitCodes();
        if (unitCodes == null|| unitCodes.isEmpty() ){
            unitCodes = tokenService.getLoginUserUnitCodes(httpServletRequest);
            monitorPoint.setUnitCodes(unitCodes);
        }
        startPage(monitorPoint.getPageNum(),monitorPoint.getPageSize());
        List<MonitorPoint> monitorPoints = monitorPointService.selectMonitorsDetailForUnitCodes(monitorPoint );
        //TODO 随后处理监控点对应的算法 10/24 先进行注释
//        for (MonitorPoint m : monitorPoints) {
//            m.setAlgorithmList(algorithmService.algorithmsInTheMonitor(m.getApeId()));
//        }
        return getDataTable(monitorPoints);
    }

    /**
     * 查询监控点的详情和监控点的视频质量监测结果
     * @param resourceTreeNodeId
     * @param diagnosisResult
     * @param diagnosisStartTime
     * @param diagnosisEndTime
     * @return
     */
    @GetMapping("selectMonitorPointsAndDiagnosisResult")
    public TableDataInfo selectMonitorPointsAndDiagnosisResult(String treeType, Integer resourceTreeNodeId,
                                                               String diagnosisResult, Date diagnosisStartTime,
                                                               Date diagnosisEndTime, String monitorPointName) {
        startPage();
        List<MonitorPointDiagnosisResultVo> resList = monitorPointService.selectMonitorsDiagnosisResult(treeType, resourceTreeNodeId, diagnosisResult, diagnosisStartTime, diagnosisEndTime, monitorPointName);
        return getDataTable(resList);
    }


    @PostMapping("selectMonitorPointsAndDiagnosisResult2/old")
    public TableDataInfo selectLastDiagnosisResultold(@RequestBody HashMap param)
    {
        //return videoDiagnosisController.selectLastDiagnosisResult(param);
        param.put("page_num", 1);
        param.put("page_size", 999999);

        Integer pageNum = (Integer) param.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) param.getOrDefault("pageSize", 10);
//        setDiagnosisNodeSet(param);
        HashSet<String> color_cast = getSet(param, "color_cast");
        HashSet<String> contrast_ratio = getSet(param,"contrast_ratio");
        HashSet<String> cross_striation =  getSet(param,"cross_striation");
        HashSet<String> definition = getSet(param, "definition");
        HashSet<String> freeze = getSet(param, "freeze");
        HashSet<String> high_luminance = getSet(param,"high_luminance");
        HashSet<String> jitter = getSet(param,"jitter");
        HashSet<String> loss =  getSet(param,"loss");
        HashSet<String> low_luminance = getSet(param,"low_luminance");
        HashSet<String> noise =  getSet(param,"noise");
        HashSet<String> occlusion = getSet(param,"occlusion");
        HashSet<String> rolling_stripe = getSet(param,"rolling_stripe");
        HashSet<String> scene_change = getSet(param,"scene_change");
        HashSet<String> stripe =  getSet(param,"stripe");
        HashSet<String> transverse_wave = getSet(param,"transverse_wave");
        String[] ownerApsNames = (String[])param.get("ownerApsNames");
        if (ownerApsNames == null) {
            ownerApsNames = new String[0];
        }
        HashSet<String> ownerApsNamesSet = new HashSet<>(Arrays.asList(ownerApsNames));
        String monitorDiagnosisResultListJsonStr = jyService.getLastVideoDiagnosisResult(param);

        List<MonitorPointDiagnosisResultVo> resList = filterAndSortDiagnosisResult(monitorDiagnosisResultListJsonStr,ownerApsNamesSet, color_cast, contrast_ratio, cross_striation, definition, freeze, high_luminance, jitter, loss, low_luminance, noise, occlusion, rolling_stripe, scene_change, stripe, transverse_wave);
        int resListSize = resList.size();
        int total = resListSize;
        int start = (pageNum - 1) * pageSize ;
        if (start > resListSize - 1) {
            start = 0;
        }
        int end = Math.min(start + pageSize, resListSize);

        resList = resList.subList(start, end);

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(resList);
        rspData.setTotal(total);
        return rspData;
    }

    /**
     * 10/24 注释 改用新版
     * @param param
     * @return
     */
    @PostMapping("selectMonitorPointsAndDiagnosisResult2/v2")
    public TableDataInfo selectLastDiagnosisResult(@RequestBody HashMap param)
    {
        TableDataInfo rspData = new TableDataInfo();
        if(VIDEO_MANUFACTURER_NAME.equals("极云")){
            rspData = selectLastDiagnosisResultByJY(param);
        }else if(VIDEO_MANUFACTURER_NAME.equals("海康")){
            rspData = selectLastDiagnosisResultByHK(new TUnitConfig());
        }
        List<?> rows = rspData.getRows();
        return rspData;
    }
    /**
     * 10/24 使用新版 新增煤矿id筛选
     * 默认选择第一个 集团查询
     * @param
     * @return
     */
    @PostMapping("selectMonitorPointsAndDiagnosisResult2")
    public TableDataInfo selectLastDiagnosisResultForUnitCodes(@RequestBody HashMap param)
    {
        TableDataInfo rspData = new TableDataInfo();
        try {
            if(VIDEO_MANUFACTURER_NAME.equals("极云")){

                rspData = selectLastDiagnosisResultByJYForUnitCodes(param);
            }else if(VIDEO_MANUFACTURER_NAME.equals("海康")){
                rspData = selectLastDiagnosisResultByHKForUnitCodes(null);
            }
            List<?> rows = rspData.getRows();
        }catch (Exception e){
            System.out.println(e);
            rspData.setRows(new ArrayList<>());
            rspData.setCode(200);

        }


        return rspData;
    }

    TableDataInfo selectLastDiagnosisResultByJY( HashMap param){
        //return videoDiagnosisController.selectLastDiagnosisResult(param);
        param.put("page_num", 1);
        param.put("page_size", 999999);

        Integer pageNum = (Integer) param.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) param.getOrDefault("pageSize", 10);
//        setDiagnosisNodeSet(param);
        HashSet<String> color_cast = getSet(param, "color_cast");
        HashSet<String> contrast_ratio = getSet(param,"contrast_ratio");
        HashSet<String> cross_striation =  getSet(param,"cross_striation");
        HashSet<String> definition = getSet(param, "definition");
        HashSet<String> freeze = getSet(param, "freeze");
        HashSet<String> high_luminance = getSet(param,"high_luminance");
        HashSet<String> jitter = getSet(param,"jitter");
        HashSet<String> loss =  getSet(param,"loss");
        HashSet<String> low_luminance = getSet(param,"low_luminance");
        HashSet<String> noise =  getSet(param,"noise");
        HashSet<String> occlusion = getSet(param,"occlusion");
        HashSet<String> rolling_stripe = getSet(param,"rolling_stripe");
        HashSet<String> scene_change = getSet(param,"scene_change");
        HashSet<String> stripe =  getSet(param,"stripe");
        HashSet<String> transverse_wave = getSet(param,"transverse_wave");
        String[] ownerApsNames = (String[])param.get("ownerApsNames");
        if (ownerApsNames == null) {
            ownerApsNames = new String[0];
        }
        HashSet<String> ownerApsNamesSet = new HashSet<>(Arrays.asList(ownerApsNames));
        String monitorDiagnosisResultListJsonStr = jyService.getLastVideoDiagnosisResult(param);

        List<MonitorPointDiagnosisResultVo> resList = filterAndSortDiagnosisResult(monitorDiagnosisResultListJsonStr,
                ownerApsNamesSet, color_cast, contrast_ratio, cross_striation, definition, freeze, high_luminance,
                jitter, loss, low_luminance, noise, occlusion, rolling_stripe, scene_change, stripe, transverse_wave);
        int resListSize = resList.size();
        int total = resListSize;
        int start = (pageNum - 1) * pageSize ;
        if (start > resListSize - 1) {
            start = 0;
        }
        int end = Math.min(start + pageSize, resListSize);

        resList = resList.subList(start, end);
        MonitorPointDiagnosisResultVo monitorPointDiagnosisResultVo = resList.get(0);
        monitorPointDiagnosisResultVo.setPictureUrl("http://123.249.34.48/images/wdaqm.jpg");
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(resList);
        rspData.setTotal(total);
        return rspData;
    }

    TableDataInfo selectLastDiagnosisResultByJYForUnitCodes(HashMap param){
        //return videoDiagnosisController.selectLastDiagnosisResult(param);

        param.put("page_num", 1);
        param.put("page_size", 999999);
        Long unitCode = (Long)param.get("unitCode");
        Integer pageNum = (Integer) param.getOrDefault("pageNum", 1);
        Integer pageSize = (Integer) param.getOrDefault("pageSize", 10);
//        setDiagnosisNodeSet(param);
        HashSet<String> color_cast = getSet(param, "color_cast");
        HashSet<String> contrast_ratio = getSet(param,"contrast_ratio");
        HashSet<String> cross_striation =  getSet(param,"cross_striation");
        HashSet<String> definition = getSet(param, "definition");
        HashSet<String> freeze = getSet(param, "freeze");
        HashSet<String> high_luminance = getSet(param,"high_luminance");
        HashSet<String> jitter = getSet(param,"jitter");
        HashSet<String> loss =  getSet(param,"loss");
        HashSet<String> low_luminance = getSet(param,"low_luminance");
        HashSet<String> noise =  getSet(param,"noise");
        HashSet<String> occlusion = getSet(param,"occlusion");
        HashSet<String> rolling_stripe = getSet(param,"rolling_stripe");
        HashSet<String> scene_change = getSet(param,"scene_change");
        HashSet<String> stripe =  getSet(param,"stripe");
        HashSet<String> transverse_wave = getSet(param,"transverse_wave");
        String[] ownerApsNames = (String[])param.get("ownerApsNames");
        if (ownerApsNames == null) {
            ownerApsNames = new String[0];
        }
        HashSet<String> ownerApsNamesSet = new HashSet<>(Arrays.asList(ownerApsNames));
        // 设置查询条件
        TUnitConfig queryCondition = new TUnitConfig();
        queryCondition.setUnitCode(unitCode);
        List<TUnitConfig> tUnitConfigs = iTUnitConfigService.selectTUnitConfigList(queryCondition);
        TUnitConfig tUnitConfig = tUnitConfigs.get(0);
        String monitorDiagnosisResultListJsonStr = jyService.getLastVideoDiagnosisResultForUnitCodes(tUnitConfig,param);

        List<MonitorPointDiagnosisResultVo> resList = filterAndSortDiagnosisResultForUnitCodes( tUnitConfig,monitorDiagnosisResultListJsonStr,
                ownerApsNamesSet, color_cast, contrast_ratio, cross_striation, definition, freeze, high_luminance,
                jitter, loss, low_luminance, noise, occlusion, rolling_stripe, scene_change, stripe, transverse_wave);
        int resListSize = resList.size();
        int total = resListSize;
        int start = (pageNum - 1) * pageSize ;
        if (start > resListSize - 1) {
            start = 0;
        }
        int end = Math.min(start + pageSize, resListSize);

        resList = resList.subList(start, end);
        //赋值 unitCode
        resList.forEach(resultVo -> resultVo.setUnitCode(unitCode));

        Map<Long, SysDept> deptMap = genericMethodsService.getDeptMap();

        // 遍历 alarmEvents 列表，根据 unitCode 匹配 deptName 并赋值给 unitName
        for (MonitorPointDiagnosisResultVo Diagnosis : resList) {
            SysDept dept = deptMap.get(Diagnosis.getUnitCode());
            if (dept != null) {
                System.out.println(dept.getDeptName());
                Diagnosis.setUnitName(dept.getDeptName());
            }
        }
//        /**
//         * 临时为诊断列表添加一张图
//         */
//        MonitorPointDiagnosisResultVo monitorPointDiagnosisResultVo = resList.get(0);
//        monitorPointDiagnosisResultVo.setPictureUrl("http://123.249.34.48/images/wdaqm.jpg");
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(resList);
        rspData.setTotal(total);
        return rspData;
    }

    TableDataInfo selectLastDiagnosisResultByHK( TUnitConfig tUnitConfig){

        TDiagnosisData tDiagnosisData = new TDiagnosisData();
        List<TDiagnosisData> TDiagnosisDatas = tDiagnosisDataService.selectTDiagnosisDataList(tDiagnosisData);
        List<MonitorPointDiagnosisResultVo> resList = new ArrayList<>();

        for (TDiagnosisData data :TDiagnosisDatas){
            MonitorPointDiagnosisResultVo monitorPointDiagnosisResultVo = new MonitorPointDiagnosisResultVo();
            String equipmentIp = data.getEquipmentIp();
            String equipmentName = data.getEquipmentName();
            String diagnosisImageUrl = data.getDiagnosisImageUrl();
            String diagnosisType = data.getDiagnosisType();
            Integer diagnosisResult = null;

            String vcrIp = data.getVcrIp();
            Date createTime = data.getCreateTime();
            String db1011 = data.getDb101();
            // 创建一个 SimpleDateFormat 实例，指定日期/时间格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            // 将 Date 转换为字符串
            String createTimeStr = sdf.format(createTime);
            MonitorPoint monitorPoint = new MonitorPoint();
            List<MonitorPoint> monitorPoints = monitorPointService.selectAllMonitorPoints2(monitorPoint.setApeId(convertIpToNumeric(equipmentIp)));
            String db101 = data.getDb101();//视频抖动
            String db102 = data.getDb102();//条纹干扰
            String db103 = data.getDb103();//视频丢失
            String db104 = data.getDb104();//视频遮挡
            String db105 = data.getDb105();//视频冻结
            String db106 = data.getDb106();//高亮度
            String db107 = data.getDb107();//低亮度
            String db108 = data.getDb108();//视频噪声
            String db109 = data.getDb109();//偏色
            String db110 = data.getDb110();//清晰度
            String db111 = data.getDb111();//场景变化
            String db112 = data.getDb112();//对比度
            String db113 = data.getDb113();//横纹干扰
            String db114 = data.getDb114();//滚动条纹
            String db115 = data.getDb115();//横波干扰

            monitorPointDiagnosisResultVo.setApeId(convertIpToNumeric(equipmentIp));
            monitorPointDiagnosisResultVo.setMonitorPointName(equipmentName);
            monitorPointDiagnosisResultVo.setPictureUrl(diagnosisImageUrl);
            monitorPointDiagnosisResultVo.setOwnerApsName(monitorPoints.get(0).getOwnerApsName());
            monitorPointDiagnosisResultVo.setOwnerApsIp(monitorPoints.get(0).getOwnerApsIp());
            monitorPointDiagnosisResultVo.setDiagnosisTime(createTimeStr);
            monitorPointDiagnosisResultVo.setDiagnosisResultName(diagnosisType);
            monitorPointDiagnosisResultVo.setDiagnosisResult(convertNameToNumeric(diagnosisType));
            //偏色
            monitorPointDiagnosisResultVo.setColorCastName(db109);
            monitorPointDiagnosisResultVo.setColorCast(convertDiagnosisNameToNumeric(db109));
            //对比度
            monitorPointDiagnosisResultVo.setContrastRatio(convertDiagnosisNameToNumeric(db112));
            monitorPointDiagnosisResultVo.setContrastRatioName(db112);
            //横纹干扰
            monitorPointDiagnosisResultVo.setCrossStriation(convertDiagnosisNameToNumeric(db113));
            monitorPointDiagnosisResultVo.setCrossStriationName(db113);
            //清晰度
            monitorPointDiagnosisResultVo.setDefinition(convertDiagnosisNameToNumeric(db110));
            monitorPointDiagnosisResultVo.setDefinitionName(db110);
            //视频冻结
            monitorPointDiagnosisResultVo.setFreeze(convertDiagnosisNameToNumeric(db105));
            monitorPointDiagnosisResultVo.setFreezeName(db105);
            //高亮度
            monitorPointDiagnosisResultVo.setHighLuminance(convertDiagnosisNameToNumeric(db106));
            monitorPointDiagnosisResultVo.setHighLuminanceName(db106);
            //视频抖动
            monitorPointDiagnosisResultVo.setJitter(convertDiagnosisNameToNumeric(db101));
            monitorPointDiagnosisResultVo.setJitterName(db101);
            //视频丢失
            monitorPointDiagnosisResultVo.setLoss(convertDiagnosisNameToNumeric(db103));
            monitorPointDiagnosisResultVo.setLossName(db103);
            //低亮度
            monitorPointDiagnosisResultVo.setLowLuminance(convertDiagnosisNameToNumeric(db107));
            monitorPointDiagnosisResultVo.setLowLuminanceName(db107);
            //视频噪声
            monitorPointDiagnosisResultVo.setNoise(convertDiagnosisNameToNumeric(db108));
            monitorPointDiagnosisResultVo.setNoiseName(db108);
            //视频遮挡
            monitorPointDiagnosisResultVo.setOcclusion(convertDiagnosisNameToNumeric(db104));
            monitorPointDiagnosisResultVo.setOcclusionName(db104);
            //滚动条纹
            monitorPointDiagnosisResultVo.setRollingStripe(convertDiagnosisNameToNumeric(db114));
            monitorPointDiagnosisResultVo.setRollingStripeName(db114);
            //场景变化
            monitorPointDiagnosisResultVo.setSceneChange(convertDiagnosisNameToNumeric(db111));
            monitorPointDiagnosisResultVo.setSceneChangeName(db111);
            //条纹干扰
            monitorPointDiagnosisResultVo.setStripe(convertDiagnosisNameToNumeric(db102));
            monitorPointDiagnosisResultVo.setStripeName(db102);
            //横波干扰
            monitorPointDiagnosisResultVo.setTransverseWave(convertDiagnosisNameToNumeric(db115));
            monitorPointDiagnosisResultVo.setTransverseWaveName(db115);
            resList.add(monitorPointDiagnosisResultVo);
        }


        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(resList);
        rspData.setTotal(TDiagnosisDatas.size());
        return rspData;
    }


    TableDataInfo selectLastDiagnosisResultByHKForUnitCodes( TUnitConfig tUnitConfig){

        TDiagnosisData tDiagnosisData = new TDiagnosisData();
        List<TDiagnosisData> TDiagnosisDatas = tDiagnosisDataService.selectTDiagnosisDataList(tDiagnosisData);
        List<MonitorPointDiagnosisResultVo> resList = new ArrayList<>();

        for (TDiagnosisData data :TDiagnosisDatas){
            MonitorPointDiagnosisResultVo monitorPointDiagnosisResultVo = new MonitorPointDiagnosisResultVo();
            String equipmentIp = data.getEquipmentIp();
            String equipmentName = data.getEquipmentName();
            String diagnosisImageUrl = data.getDiagnosisImageUrl();
            String diagnosisType = data.getDiagnosisType();
            Integer diagnosisResult = null;

            String vcrIp = data.getVcrIp();
            Date createTime = data.getCreateTime();
            String db1011 = data.getDb101();
            // 创建一个 SimpleDateFormat 实例，指定日期/时间格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            // 将 Date 转换为字符串
            String createTimeStr = sdf.format(createTime);
            MonitorPoint monitorPoint = new MonitorPoint();
            List<MonitorPoint> monitorPoints = monitorPointService.selectAllMonitorPoints2(monitorPoint.setApeId(convertIpToNumeric(equipmentIp)));
            String db101 = data.getDb101();//视频抖动
            String db102 = data.getDb102();//条纹干扰
            String db103 = data.getDb103();//视频丢失
            String db104 = data.getDb104();//视频遮挡
            String db105 = data.getDb105();//视频冻结
            String db106 = data.getDb106();//高亮度
            String db107 = data.getDb107();//低亮度
            String db108 = data.getDb108();//视频噪声
            String db109 = data.getDb109();//偏色
            String db110 = data.getDb110();//清晰度
            String db111 = data.getDb111();//场景变化
            String db112 = data.getDb112();//对比度
            String db113 = data.getDb113();//横纹干扰
            String db114 = data.getDb114();//滚动条纹
            String db115 = data.getDb115();//横波干扰

            monitorPointDiagnosisResultVo.setApeId(convertIpToNumeric(equipmentIp));
            monitorPointDiagnosisResultVo.setMonitorPointName(equipmentName);
            monitorPointDiagnosisResultVo.setPictureUrl(diagnosisImageUrl);
            monitorPointDiagnosisResultVo.setOwnerApsName(monitorPoints.get(0).getOwnerApsName());
            monitorPointDiagnosisResultVo.setOwnerApsIp(monitorPoints.get(0).getOwnerApsIp());
            monitorPointDiagnosisResultVo.setDiagnosisTime(createTimeStr);
            monitorPointDiagnosisResultVo.setDiagnosisResultName(diagnosisType);
            monitorPointDiagnosisResultVo.setDiagnosisResult(convertNameToNumeric(diagnosisType));
            //偏色
            monitorPointDiagnosisResultVo.setColorCastName(db109);
            monitorPointDiagnosisResultVo.setColorCast(convertDiagnosisNameToNumeric(db109));
            //对比度
            monitorPointDiagnosisResultVo.setContrastRatio(convertDiagnosisNameToNumeric(db112));
            monitorPointDiagnosisResultVo.setContrastRatioName(db112);
            //横纹干扰
            monitorPointDiagnosisResultVo.setCrossStriation(convertDiagnosisNameToNumeric(db113));
            monitorPointDiagnosisResultVo.setCrossStriationName(db113);
            //清晰度
            monitorPointDiagnosisResultVo.setDefinition(convertDiagnosisNameToNumeric(db110));
            monitorPointDiagnosisResultVo.setDefinitionName(db110);
            //视频冻结
            monitorPointDiagnosisResultVo.setFreeze(convertDiagnosisNameToNumeric(db105));
            monitorPointDiagnosisResultVo.setFreezeName(db105);
            //高亮度
            monitorPointDiagnosisResultVo.setHighLuminance(convertDiagnosisNameToNumeric(db106));
            monitorPointDiagnosisResultVo.setHighLuminanceName(db106);
            //视频抖动
            monitorPointDiagnosisResultVo.setJitter(convertDiagnosisNameToNumeric(db101));
            monitorPointDiagnosisResultVo.setJitterName(db101);
            //视频丢失
            monitorPointDiagnosisResultVo.setLoss(convertDiagnosisNameToNumeric(db103));
            monitorPointDiagnosisResultVo.setLossName(db103);
            //低亮度
            monitorPointDiagnosisResultVo.setLowLuminance(convertDiagnosisNameToNumeric(db107));
            monitorPointDiagnosisResultVo.setLowLuminanceName(db107);
            //视频噪声
            monitorPointDiagnosisResultVo.setNoise(convertDiagnosisNameToNumeric(db108));
            monitorPointDiagnosisResultVo.setNoiseName(db108);
            //视频遮挡
            monitorPointDiagnosisResultVo.setOcclusion(convertDiagnosisNameToNumeric(db104));
            monitorPointDiagnosisResultVo.setOcclusionName(db104);
            //滚动条纹
            monitorPointDiagnosisResultVo.setRollingStripe(convertDiagnosisNameToNumeric(db114));
            monitorPointDiagnosisResultVo.setRollingStripeName(db114);
            //场景变化
            monitorPointDiagnosisResultVo.setSceneChange(convertDiagnosisNameToNumeric(db111));
            monitorPointDiagnosisResultVo.setSceneChangeName(db111);
            //条纹干扰
            monitorPointDiagnosisResultVo.setStripe(convertDiagnosisNameToNumeric(db102));
            monitorPointDiagnosisResultVo.setStripeName(db102);
            //横波干扰
            monitorPointDiagnosisResultVo.setTransverseWave(convertDiagnosisNameToNumeric(db115));
            monitorPointDiagnosisResultVo.setTransverseWaveName(db115);
            resList.add(monitorPointDiagnosisResultVo);
        }


        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(resList);
        rspData.setTotal(TDiagnosisDatas.size());
        return rspData;
    }

    public static String convertIpToNumeric(String ip) {
        String[] parts = ip.split("\\."); // 使用正则表达式split，以点分隔IP地址
        StringBuilder sb = new StringBuilder();
        for (String part : parts) {
            // Integer.parseInt将字符串转换为整数，然后toString转回字符串形式，format确保至少有3位数，不够的前面补0
            sb.append(String.format("%03d", Integer.parseInt(part)));
        }
        return sb.toString();
    }

    public static Integer convertNameToNumeric(String name) {
        Integer Numeric=null;
        if(name.equals("达标")){
            Numeric=1;
        }else if(name.equals("一般")){
            Numeric=2;
        }else if(name.equals("失败")){
            Numeric=3;
        }else if(name.equals("很差")){
            Numeric=4;
        }
        return Numeric;
    }

    public static Integer convertDiagnosisNameToNumeric(String name) {
        Integer Numeric=null;
        if(name.equals("正常")){
            Numeric=1;
        }else if(name.equals("")){
            Numeric=5;
        }
        return Numeric;
    }

    /**
     *
     * 修改监控点和树结点以及场所的关联关系
     * 更新监控点和树结点的关联关系时，需要传入树节点的id
     */
//    @PutMapping("update2")
//    public AjaxResult updateTreeNodeAndStandPlaceItBelongs(String monitorId, Integer nodeId, Long standPlaceId) {
//        if (monitorId == null) {
//            return AjaxResult.error("请传入监控点的id");
//        }
//        return AjaxResult.success(monitorPointService.updateTreeNodeAndStandPlaceItBelongs(monitorId, nodeId, standPlaceId));
//    }
    @PutMapping("update2")
    public AjaxResult updateTreeNodeAndStandPlaceItBelongs(String monitorId, String treeType, Integer nodeId, Long standPlaceId) {
        if (monitorId == null) {
            return AjaxResult.error("请传入监控点的id");
        }
        if (monitorId == null) {
            return AjaxResult.error("请传入监控点的id");
        }

        if(nodeId != null && videoResourceTreeService.selectTreeNodeById(nodeId) != null) {
            monitorPointService.delMonitorAndTreeNodeRelInTheTreeType(monitorId, treeType);
            monitorPointService.addMonitorAndTreeNodeRel(monitorId, nodeId);
        }else {
            monitorPointService.delMonitorAndTreeNodeRelInTheTreeType(monitorId, treeType);
        }

        if (standPlaceId != null) {
            tVideoStandPlaceService.delMonitorRelAllPlace(monitorId);
            //场所的名称
            String placeAddress = tVideoStandPlaceService.selectTVideoStandPlaceById(standPlaceId).getAddress();
            tVideoStandPlaceService.addMonitorRelPlace(placeAddress, monitorId);
        }else {
            tVideoStandPlaceService.delMonitorRelAllPlace(monitorId);
        }
        return AjaxResult.success();
    }

    private List<MonitorPointDiagnosisResultVo> filterAndSortDiagnosisResult
            (String monitorDiagnosisResultListJsonStr, HashSet<String> ownerApsNameSet, HashSet color_cast_set,
             HashSet contrast_ratio_set, HashSet cross_striation_set, HashSet definition_set, HashSet freeze_set,
             HashSet high_luminance_set, HashSet jitter_set, HashSet loss_set, HashSet low_luminance_set, HashSet noise_set,
             HashSet occlusion_set, HashSet rolling_stripe_set, HashSet scene_change_set, HashSet stripe_set, HashSet transverse_wave_set)
    {
        JSONArray monitorDiagnosisResultJsonArray = JSONObject.parseObject(monitorDiagnosisResultListJsonStr).getJSONObject("data").getJSONArray("data");

        LinkedList<MonitorPointDiagnosisResultVo> res = new LinkedList<>();
        Map<Integer, String> videoDiagnosisDicMap = new HashMap<Integer, String>() {{
            put(1, "正常");
            put(2, "预警");
            put(3, "报警");
            put(4, "未检测");
            put(5, "检测失败");
        }};
        HashMap<Integer, String> diagnosisResultDicMap = new HashMap<Integer, String>() {{
            put(1, "正常");
            put(2, "一般");
            put(3, "很差");
            put(4, "失败");
        }};

        // 查询所有监控点apeId和ownerApsName的映射关系
        List<MonitorPoint> allMonitors = monitorPointService.selectAllMonitorPoints();
        HashMap<String, MonitorPoint> monitorsHashMap = new HashMap<>(allMonitors.size());

        for (MonitorPoint monitor : allMonitors) {
            monitorsHashMap.put(monitor.getApeId(), monitor);
        }

        for (int i = 0;  i < monitorDiagnosisResultJsonArray.size(); i++) {
            JSONObject j = monitorDiagnosisResultJsonArray.getJSONObject(i);

            MonitorPoint monitorInfo = monitorsHashMap.get(j.getString("ape_id"));

            MonitorPointDiagnosisResultVo monitorDiagnosisResult = new MonitorPointDiagnosisResultVo();
            if (monitorInfo != null) {
                monitorDiagnosisResult.setMonitorPointName(monitorInfo.getName());
                monitorDiagnosisResult.setOwnerApsName(monitorInfo.getOwnerApsName());
                monitorDiagnosisResult.setOwnerApsIp(monitorInfo.getOwnerApsIp());
                monitorDiagnosisResult.setIsOnline(monitorInfo.getIsOnline());
                monitorDiagnosisResult.setIsOnlineName(monitorInfo.getIsOnline().equals("1") ? "在线" : "离线");
                monitorDiagnosisResult.setModel(monitorInfo.getModel());
            }
            monitorDiagnosisResult.setApeId(j.getString("ape_id"))
                                    .setPictureUrl(j.getString("picture_url"))
                                    .setDiagnosisTime(j.getString("diagnosis_time"))
                                    .setDiagnosisResult(j.getInteger("result"))
                                    .setDiagnosisResultName(diagnosisResultDicMap.get(j.getInteger("result")))
                                    .setDiagnosisResultReason(j.getString("diagnosis_result_reason"))
                                    .setColorCast(j.getInteger("color_cast"))
                                    .setColorCastName(videoDiagnosisDicMap.get(j.getInteger("color_cast")))
                                    .setContrastRatio(j.getInteger("contrast_ratio"))
                                    .setContrastRatioName(videoDiagnosisDicMap.get(j.getInteger("contrast_ratio")))
                                    .setCrossStriation(j.getInteger("cross_striation"))
                                    .setCrossStriationName(videoDiagnosisDicMap.get(j.getInteger("cross_striation")))
                                    .setDefinition(j.getInteger("definition"))
                                    .setDefinitionName(videoDiagnosisDicMap.get(j.getInteger("definition")))
                                    .setFreeze(j.getInteger("freeze"))
                                    .setFreezeName(videoDiagnosisDicMap.get(j.getInteger("freeze")))
                                    .setHighLuminance(j.getInteger("high_luminance"))
                                    .setHighLuminanceName(videoDiagnosisDicMap.get(j.getInteger("high_luminance")))
                                    .setJitter(j.getInteger("jitter"))
                                    .setJitterName(videoDiagnosisDicMap.get(j.getInteger("jitter")))
                                    .setLoss(j.getInteger("loss"))
                                    .setLossName(videoDiagnosisDicMap.get(j.getInteger("loss")))
                                    .setLowLuminance(j.getInteger("low_luminance"))
                                    .setLowLuminanceName(videoDiagnosisDicMap.get(j.getInteger("low_luminance")))
                                    .setNoise(j.getInteger("noise"))
                                    .setNoiseName(videoDiagnosisDicMap.get(j.getInteger("noise")))
                                    .setOcclusion(j.getInteger("occlusion"))
                                    .setOcclusionName(videoDiagnosisDicMap.get(j.getInteger("occlusion")))
                                    .setRollingStripe(j.getInteger("rolling_stripe"))
                                    .setRollingStripeName(videoDiagnosisDicMap.get(j.getInteger("rolling_stripe")))
                                    .setSceneChange(j.getInteger("scene_change"))
                                    .setSceneChangeName(videoDiagnosisDicMap.get(j.getInteger("scene_change")))
                                    .setStripe(j.getInteger("stripe"))
                                    .setStripeName(videoDiagnosisDicMap.get(j.getInteger("stripe")))
                                    .setTransverseWave(j.getInteger("transverse_wave"))
                                    .setTransverseWaveName(videoDiagnosisDicMap.get(j.getInteger("transverse_wave")))
                                    .setPictureUrl("http://"+JY_IP+":"+JY_LOGIN_PORT+"/"+monitorDiagnosisResult.getPictureUrl()+"?timestamp=1");


            if (!ownerApsNameSet.isEmpty() && !ownerApsNameSet.contains(monitorDiagnosisResult.getOwnerApsName())) {
                continue;
            }

            boolean isAddResult  =  color_cast_set.contains(j.getString("color_cast")) &&
                                    contrast_ratio_set.contains(j.getString("contrast_ratio")) &&
                                    cross_striation_set.contains(j.getString("cross_striation")) &&
                                    definition_set.contains(j.getString("definition")) &&
                                    freeze_set.contains(j.getString("freeze")) &&
                                    high_luminance_set.contains(j.getString("high_luminance")) &&
                                    jitter_set.contains(j.getString("jitter")) &&
                                    loss_set.contains(j.getString("loss")) &&
                                    low_luminance_set.contains(j.getString("low_luminance")) &&
                                    noise_set.contains(j.getString("noise")) &&
                                    occlusion_set.contains(j.getString("occlusion")) &&
                                    rolling_stripe_set.contains(j.getString("rolling_stripe")) &&
                                    scene_change_set.contains(j.getString("scene_change")) &&
                                    stripe_set.contains(j.getString("stripe")) &&
                                    transverse_wave_set.contains(j.getString("transverse_wave"));

            if(!isAddResult) continue;
            res.add(monitorDiagnosisResult);
        }
        Collections.sort(res, (o1, o2) -> o2.getDiagnosisTime().compareTo(o1.getDiagnosisTime()));
        return res;
    }

    private List<MonitorPointDiagnosisResultVo> filterAndSortDiagnosisResultForUnitCodes
            (TUnitConfig tUnitConfig,String monitorDiagnosisResultListJsonStr, HashSet<String> ownerApsNameSet, HashSet color_cast_set,
             HashSet contrast_ratio_set, HashSet cross_striation_set, HashSet definition_set, HashSet freeze_set,
             HashSet high_luminance_set, HashSet jitter_set, HashSet loss_set, HashSet low_luminance_set, HashSet noise_set,
             HashSet occlusion_set, HashSet rolling_stripe_set, HashSet scene_change_set, HashSet stripe_set, HashSet transverse_wave_set)
    {
        JSONArray monitorDiagnosisResultJsonArray = JSONObject.parseObject(monitorDiagnosisResultListJsonStr).getJSONObject("data").getJSONArray("data");

        LinkedList<MonitorPointDiagnosisResultVo> res = new LinkedList<>();
        Map<Integer, String> videoDiagnosisDicMap = new HashMap<Integer, String>() {{
            put(1, "正常");
            put(2, "预警");
            put(3, "报警");
            put(4, "未检测");
            put(5, "检测失败");
        }};
        HashMap<Integer, String> diagnosisResultDicMap = new HashMap<Integer, String>() {{
            put(1, "正常");
            put(2, "一般");
            put(3, "很差");
            put(4, "失败");
        }};

        // 查询所有监控点apeId和ownerApsName的映射关系
//        List<MonitorPoint> allMonitors = monitorPointService.selectAllMonitorPoints();
        List<MonitorPoint> allMonitors = monitorPointService.selectAllMonitorPointsGroup(tUnitConfig.getUnitCode());

        HashMap<String, MonitorPoint> monitorsHashMap = new HashMap<>(allMonitors.size());

        for (MonitorPoint monitor : allMonitors) {
            monitorsHashMap.put(monitor.getApeId(), monitor);
        }

        for (int i = 0;  i < monitorDiagnosisResultJsonArray.size(); i++) {
            JSONObject j = monitorDiagnosisResultJsonArray.getJSONObject(i);

            MonitorPoint monitorInfo = monitorsHashMap.get(j.getString("ape_id"));

            MonitorPointDiagnosisResultVo monitorDiagnosisResult = new MonitorPointDiagnosisResultVo();
            if (monitorInfo != null) {
                monitorDiagnosisResult.setMonitorPointName(monitorInfo.getName());
                monitorDiagnosisResult.setOwnerApsName(monitorInfo.getOwnerApsName());
                monitorDiagnosisResult.setOwnerApsIp(monitorInfo.getOwnerApsIp());
                monitorDiagnosisResult.setIsOnline(monitorInfo.getIsOnline());
                monitorDiagnosisResult.setIsOnlineName(monitorInfo.getIsOnline().equals("1") ? "在线" : "离线");
                monitorDiagnosisResult.setModel(monitorInfo.getModel());
            }
            String JY_IP = tUnitConfig.getJyIp();
            String JY_LOGIN_PORT = tUnitConfig.getLocalIpPort();
            //设置nginx代理前缀
            String nginxProxy = "http://"+SERVER_IP+":"+WEB_PORT+"/image_jy/";
            String image_url = "http://"+JY_IP+":"+JY_LOGIN_PORT+"/"+j.getString("picture_url")+"?timestamp=1";
            image_url= nginxProxy + image_url;
            monitorDiagnosisResult.setApeId(j.getString("ape_id"))
                    .setPictureUrl(image_url)
                    .setDiagnosisTime(j.getString("diagnosis_time"))
                    .setDiagnosisResult(j.getInteger("result"))
                    .setDiagnosisResultName(diagnosisResultDicMap.get(j.getInteger("result")))
                    .setDiagnosisResultReason(j.getString("diagnosis_result_reason"))
                    .setColorCast(j.getInteger("color_cast"))
                    .setColorCastName(videoDiagnosisDicMap.get(j.getInteger("color_cast")))
                    .setContrastRatio(j.getInteger("contrast_ratio"))
                    .setContrastRatioName(videoDiagnosisDicMap.get(j.getInteger("contrast_ratio")))
                    .setCrossStriation(j.getInteger("cross_striation"))
                    .setCrossStriationName(videoDiagnosisDicMap.get(j.getInteger("cross_striation")))
                    .setDefinition(j.getInteger("definition"))
                    .setDefinitionName(videoDiagnosisDicMap.get(j.getInteger("definition")))
                    .setFreeze(j.getInteger("freeze"))
                    .setFreezeName(videoDiagnosisDicMap.get(j.getInteger("freeze")))
                    .setHighLuminance(j.getInteger("high_luminance"))
                    .setHighLuminanceName(videoDiagnosisDicMap.get(j.getInteger("high_luminance")))
                    .setJitter(j.getInteger("jitter"))
                    .setJitterName(videoDiagnosisDicMap.get(j.getInteger("jitter")))
                    .setLoss(j.getInteger("loss"))
                    .setLossName(videoDiagnosisDicMap.get(j.getInteger("loss")))
                    .setLowLuminance(j.getInteger("low_luminance"))
                    .setLowLuminanceName(videoDiagnosisDicMap.get(j.getInteger("low_luminance")))
                    .setNoise(j.getInteger("noise"))
                    .setNoiseName(videoDiagnosisDicMap.get(j.getInteger("noise")))
                    .setOcclusion(j.getInteger("occlusion"))
                    .setOcclusionName(videoDiagnosisDicMap.get(j.getInteger("occlusion")))
                    .setRollingStripe(j.getInteger("rolling_stripe"))
                    .setRollingStripeName(videoDiagnosisDicMap.get(j.getInteger("rolling_stripe")))
                    .setSceneChange(j.getInteger("scene_change"))
                    .setSceneChangeName(videoDiagnosisDicMap.get(j.getInteger("scene_change")))
                    .setStripe(j.getInteger("stripe"))
                    .setStripeName(videoDiagnosisDicMap.get(j.getInteger("stripe")))
                    .setTransverseWave(j.getInteger("transverse_wave"))
                    .setTransverseWaveName(videoDiagnosisDicMap.get(j.getInteger("transverse_wave")));


            if (!ownerApsNameSet.isEmpty() && !ownerApsNameSet.contains(monitorDiagnosisResult.getOwnerApsName())) {
                continue;
            }

            boolean isAddResult  =  color_cast_set.contains(j.getString("color_cast")) &&
                    contrast_ratio_set.contains(j.getString("contrast_ratio")) &&
                    cross_striation_set.contains(j.getString("cross_striation")) &&
                    definition_set.contains(j.getString("definition")) &&
                    freeze_set.contains(j.getString("freeze")) &&
                    high_luminance_set.contains(j.getString("high_luminance")) &&
                    jitter_set.contains(j.getString("jitter")) &&
                    loss_set.contains(j.getString("loss")) &&
                    low_luminance_set.contains(j.getString("low_luminance")) &&
                    noise_set.contains(j.getString("noise")) &&
                    occlusion_set.contains(j.getString("occlusion")) &&
                    rolling_stripe_set.contains(j.getString("rolling_stripe")) &&
                    scene_change_set.contains(j.getString("scene_change")) &&
                    stripe_set.contains(j.getString("stripe")) &&
                    transverse_wave_set.contains(j.getString("transverse_wave"));

            if(!isAddResult) continue;
            res.add(monitorDiagnosisResult);
        }
        Collections.sort(res, (o1, o2) -> o2.getDiagnosisTime().compareTo(o1.getDiagnosisTime()));
        return res;
    }

    private int getTotalNumberOfMonitorDiagnosisResult(String monitorDiagnosisResultListJsonStr) {
        int res = JSONObject.parseObject(monitorDiagnosisResultListJsonStr).getJSONObject("data").getJSONObject("paging").getIntValue("total");
        return res;
    }

    private HashMap<String, Integer> countNumberOfEachDiagnosisResult(String monitorDiagnosisResultListJsonStr) {
        JSONArray jsonArray = JSONObject.parseObject(monitorDiagnosisResultListJsonStr).getJSONObject("data").getJSONArray("data");
        int normalCount = 0;
        int generalCount = 0;
        int poorCount = 0;
        int failCount = 0;

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Integer result = jsonObject.getInteger("result");
            switch (result) {
                case 1 :
                    normalCount++;
                    break;
                case 2 :
                    generalCount++;
                    break;
                case 3 :
                    poorCount++;
                    break;
                case 4 :
                    failCount++;
                    break;
            }
        }
        HashMap<String, Integer> res = new HashMap<>();
        res.put("1", normalCount);
        res.put("2", generalCount);
        res.put("3", poorCount);
        res.put("4", failCount);
        return res;
    }

    private HashMap<String, Integer> countNumberOfEachDiagnosisResultForUnitCodes(List<String> DiagnosisList) {
        // 创建一个空的 JSONArray
        JSONArray jsonArrayAll = new JSONArray();

        for (String DiagnosisResult : DiagnosisList) {
            // 解析 JSON 字符串
            JSONObject jsonObject = JSONObject.parseObject(DiagnosisResult);
            JSONArray jsonArray = jsonObject.getJSONObject("data").getJSONArray("data");

            // 将 jsonArray 中的每个元素添加到 jsonArrayAll 中
            for (Object item : jsonArray) {
                jsonArrayAll.add(item);
            }
        }

        int normalCount = 0;
        int generalCount = 0;
        int poorCount = 0;
        int failCount = 0;

        for (int i = 0; i < jsonArrayAll.size(); i++) {
            JSONObject jsonObject = jsonArrayAll.getJSONObject(i);
            Integer result = jsonObject.getInteger("result");
            switch (result) {
                case 1 :
                    normalCount++;
                    break;
                case 2 :
                    generalCount++;
                    break;
                case 3 :
                    poorCount++;
                    break;
                case 4 :
                    failCount++;
                    break;
            }
        }
        HashMap<String, Integer> res = new HashMap<>();
        res.put("1", normalCount);
        res.put("2", generalCount);
        res.put("3", poorCount);
        res.put("4", failCount);
        return res;
    }
    private List<HistogramVo> buildDiagnosisResultList(HashMap<String, Integer> diagnosisResultMap) {
        List<HistogramVo> resList = new ArrayList<>();
        //
        HistogramVo histogramVo1 = new HistogramVo();
        histogramVo1.setX_axis("达标");
        histogramVo1.setY_axis(diagnosisResultMap.get("1"));
        //
        HistogramVo histogramVo2 = new HistogramVo();
        histogramVo2.setX_axis("一般");
        histogramVo2.setY_axis(diagnosisResultMap.get("2"));
        //
        HistogramVo histogramVo3 = new HistogramVo();
        histogramVo3.setX_axis("很差");
        histogramVo3.setY_axis(diagnosisResultMap.get("3"));
        //
        HistogramVo histogramVo4 = new HistogramVo();
        histogramVo4.setX_axis("失败");
        histogramVo4.setY_axis(diagnosisResultMap.get("4"));
        //
        resList.add(histogramVo1);
        resList.add(histogramVo2);
        resList.add(histogramVo3);
        resList.add(histogramVo4);

        return resList;
    }

    HashSet<String> getSet(HashMap map, String key) {
        HashSet<String> set = new HashSet<>();
        String[] arr = new String[]{ "1", "2", "3", "4", "5"};
        String strVal = (String) map.get(key);
        if (strVal != null && strVal.length() != 0) {
            arr = strVal.split(",");
        }
        Collections.addAll(set,arr);
        return set;
    }
    private HashMap<String, Object> setDiagnosisNodeSet(HashMap<String, Object> param) {
        List<String> diagnosticItems = Arrays.asList("color_cast", "contrast_ratio", "cross_striation", "definition", "freeze", "high_luminance", "jitter", "loss", "low_luminance", "noise", "occlusion", "rolling_stripe", "scene_change", "stripe", "transverse_wave");
        for (String diagnosticItem : diagnosticItems) {
            String[] arr = new String[]{ "1", "2", "3", "4", "5"};
            String diagnosticItemVal = (String) param.get(diagnosticItem);
            if (diagnosticItemVal != null && diagnosticItemVal.length() != 0) {
                arr = diagnosticItemVal.split(",");
            }
            HashSet<String> set = new HashSet<>();
            Collections.addAll(set,arr);
            param.put(diagnosticItem, set);
        }
        return param;
    }


}
